<?php

namespace origin;

/**
 * curl打印
 * @author decezz@qq.com
 */
class CurlDump
{

    /**
     * curl
     */
    public $curl = 'curl';

    /**
     * body
     */
    public $body = [];

    /**
     * header
     */
    public $header = [];

    /**
     * method
     */
    public $method = '';

    /**
     * content type
     */
    public $type = '';

    /**
     * content type list
     */
    public $contentTypeList = [
        'urlencoded'    => 'application/x-www-form-urlencoded',
        'data'          => 'multipart/form-data',
        'json'          => 'application/json',
    ];

    /**
     * 内容输出
     * @author decezz@qq.com
     * @param int $url
     * @param string $type
     * @return void
     */
    public function echo($url, $type = 'json')
    {
        $this->setType($type);
        $this->setHeader();
        $this->setBody();
        $this->curl .= sprintf(' "%s"', $url);
        return $this->curl;
    }

    /**
     * @param string $url
     * @param string $type
     * 输出curl请求
     */
    public function json($url)
    {
        $this->setType('json');
        $this->setHeader();
        $this->curl .= sprintf(' --data-binary \'%s\'', json_encode($this->body));
        $this->curl .= sprintf(' --compressed \'%s\'', $url);
        return $this->curl;
    }

    /**
     * 设置header
     * @access public
     * @param  array $header
     */
    public function header(array $header)
    {
        $this->header = array_merge($this->header, $header);
        return $this;
    }

    /**
     * 设置method
     * @access public
     * @param  string $method
     */
    public function method(string $method)
    {
        $this->method = $method;
        $this->curl .= sprintf(' -X \'%s\'', $method);
        return $this;
    }

    /**
     * 设置body
     * @access public
     * @param  array $body
     */
    public function body(array $body)
    {
        $this->body = array_merge($this->body, $body);
        return $this;
    }

    /**
     * 设置Content-Type
     * @access public
     * @param  string $type
     */
    public function setType($type)
    {
        $this->type = $type;
        $content = array_key_exists($type, $this->contentTypeList) ? $this->contentTypeList[$type] : $this->contentTypeList['urlencoded'] ;
        $this->header(['Content-Type'=>$content]);
    }

    /**
     * 处理设定header
     * @access protected
     */
    protected function setHeader()
    {
        // 遍历header头信息
        foreach ($this->header as $key => $val) {
            $this->curl .= sprintf(" -H '%s: %s'", $key, $val);
        }
    }

    /**
     * 设置body
     * @access protected
     */
    protected function setBody()
    {
        if ($this->type == 'json') {
            $query = json_encode($this->body);
        } else {
            $query = http_build_query($this->body);
        }
        $this->curl .= sprintf(' -d \'%s\'', $query);
    }

}
